import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAuthStore = defineStore('auth', () => {
  const isAuthenticated = ref(false)
  const masterPassword = ref('')
  const isFirstTime = ref(false)

  const login = async (password) => {
    try {
      // 检查是否为首次使用
      const hasDataFile = await window.electronAPI.checkDataFile()
      
      if (!hasDataFile) {
        // 首次使用，设置主密码
        isFirstTime.value = true
        const success = await window.electronAPI.setupMasterPassword(password)
        if (success) {
          isAuthenticated.value = true
          masterPassword.value = password
          return { success: true, isFirstTime: true }
        }
        return { success: false, message: '设置主密码失败' }
      } else {
        // 验证现有密码
        const isValid = await window.electronAPI.verifyMasterPassword(password)
        if (isValid) {
          isAuthenticated.value = true
          masterPassword.value = password
          return { success: true, isFirstTime: false }
        }
        return { success: false, message: '密码错误' }
      }
    } catch (error) {
      console.error('登录失败:', error)
      return { success: false, message: '登录失败，请重试' }
    }
  }

  const logout = () => {
    isAuthenticated.value = false
    masterPassword.value = ''
    isFirstTime.value = false
  }

  return {
    isAuthenticated,
    masterPassword,
    isFirstTime,
    login,
    logout
  }
})
